<script setup lang="ts">
import {ref, reactive, watch, computed} from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NSelect,
  NButton,
  NScrollbar,
  NModal,
  useMessage,
  NSpin,
  NIcon,
  type FormInst,
  NDatePicker
} from 'naive-ui'
import router from '@/router'
import { onMounted } from 'vue'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { DisModel } from '@/api/receiveOrDispatch'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'
import { ErrorRound } from '@vicons/material'
import CustomVisitor from './CustomVisitor.vue'
import { subDays } from 'date-fns'

const tags = useTagStore().tags
const route = useRoute()
const props = defineProps({
  title: { type: String, default: () => '入库申请' },
  id: { type: String, default: () => null },
  flag: { type: [Number, String], default: () => null }
})
const message = useMessage()

const formValue = reactive<Record<string, any>>({
  inTime: null, //入库
  outTime: null, //出库
  reasons: '', //原因
  draft: null, //草稿状态
  entityId: null, //流程实体id
  passTypeCode: null
})

const rules: any = ref({
  inTime: {
    required: true,
    message: '请输入入库时间',
    type: 'any',
    trigger: ['change', 'blur']
  },
  outTime: {
    required: true,
    message: '请输入出库时间',
    type: 'any',
    trigger: ['change', 'blur']
  },
  reasons: {
    required: true,
    message: '请输入入库原因',
    trigger: ['input', 'blur']
  },
  passTypeCode: {
    required: true,
    trigger: ['blur', 'change'],
    message: '请选择入库类型'
  }
})

// 去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}
// 入库类型
const inoutTypeCodeList: any = ref()
const getParentCode = async () => {
  const [error, res] = await sendRequest<HttpResponse<DisModel>>({
    module: 'receiveOrDispatch',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A27'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  inoutTypeCodeList.value = res.data
}
// 开始时间选择
const handleUpdateStartTime = (v: any) => {
  formValue.inTime = v
}
// 结束时间选择
const handleUpdateEndTime = (v: any) => {
  if (overTimeSeconds.value < 0) {
    formValue.outTime = formValue.inTime
  }
}
// 日期禁用
const handleDate = (ts: any) => {
  return ts < new Date(subDays(new Date(formValue.inTime?.split(' ')[0]), 1))
}
// 日期禁用开始
const handleDateStart = (ts: any) => {
  if (!formValue.outTime) return false
  return ts > new Date(subDays(new Date(formValue.outTime), 0))
}
// 陪同人员
const inoutpersonCodeList: any = ref()
const getPersonCode = async () => {
  const [error, res] = await sendRequest({
    module: 'inStorage',
    api: 'allUserList'
  })
  if (error) return
  if (res.code !== 0) return
  inoutpersonCodeList.value = res.data.map((it: any) => {
    return { value: it.userId.toString(), label: it.userName }
  })
}
// 获取流程id
const hint = ref()
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: 'A0581'
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length
    ? res.data.workFlowList?.map((it: any) => it).join(' → ')
    : null
  spinShow.value = false
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 确定
const contentVisible = ref(false)
const formRef = ref<FormInst | null>(null)
const contentContent = ref()
const confirm = (status: number) => {
  contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
  formRef.value?.validate(async (err) => {
    if (err) return
    contentVisible.value = true
    formValue.draft = status
  })
}
// 提交
const submit = async () => {
  const tmp = JSON.parse(JSON.stringify(formValue))
  if (overTimeSeconds.value < 0) return message.error('入库时间要小于出库时间！')
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'inStorage',
      api: 'inoutUpdate',
      override: {
        data: {
          ...tmp,
          id: props.id,
          userName: userName.value
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg)
    goSubmit()
  } else {
    const [error, res] = await sendRequest({
      module: 'inStorage',
      api: 'inoutSave',
      override: {
        data: {
          ...tmp,
          id: null
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg)
    goSubmit()
  }
  contentVisible.value = false
}
// 提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}
// 获取修改详情
const userName = ref()
const getInfo = async () => {
  await getPersonCode()
  const [error, res] = await sendRequest({
    module: 'inStorage',
    api: 'inoutInfo',
    uri: {
      id: props.id
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  userName.value = res.data?.userName
  Object.keys(res.data).map((it: any) => (formValue[it] = res.data[it]))
  formValue.customIssuer = []
  await getWorkFlow()
}

//计算差秒（单位秒）
const overTimeSeconds = computed(() => {
  if (!formValue.inTime || !formValue.outTime) return '0'
  const date = Math.floor(
    (new Date(formValue.outTime).getTime() - new Date(formValue.inTime).getTime()) / 1000
  )
  return date.toString()
})
watch(
  () => props.id,
  async () => {
    if (props.title == '人员入库编辑' && props.id) {
      getInfo()
    }
  },
  { deep: true, immediate: true }
)

watch(formValue, () => {
  rules.value = {
    inTime: {
      required: true,
      message: '请输入入库时间',
      type: 'any',
      trigger: ['change', 'blur']
    },
    outTime: {
      required: true,
      message: '请输入出库时间',
      type: 'any',
      trigger: ['change', 'blur']
    },
    passTypeCode: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择入库类型'
    },
    reasons: {
      required: true,
      trigger: ['change', 'input'],
      validator: (_: any, value: any) => {
        if (!value) return new Error('请输入入库原因')
        if (value?.length > 200) return new Error('入库原因不得超过200字')
        return true
      }
    }
  }
})

onMounted(() => {
  getParentCode()
  getPersonCode()
  getWorkFlow()
})
</script>

<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">
            <div
              class="progressHint"
              v-if="hint"
            >
              <NIcon
                size="20"
                class="iconStyle"
              >
                <ErrorRound />
              </NIcon>
              <div
                style="white-space: pre-wrap"
                v-html="hint"
              ></div>
            </div>
            <div class="progress">
              <div style="display: flex; margin-right: 10rem">
                <NIcon
                  :size="20"
                  class="iconStyle"
                >
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span
                style="font-size: 18rem; flex: 1"
                :style="{ color: !workFlowList ? 'red' : '#79bb92' }"
              >
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm
                ref="formRef"
                require-mark-placement="left"
                label-placement="left"
                :rules="rules"
                :label-width="120"
                :model="formValue"
                style="width: 420rem"
                label-align="right"
              >
                <!--                <NFormItem label="入库类型:" path="passTypeCode">
                  <NSelect :options="inoutTypeCodeList" placeholder="请选择" clearable class="commonWidth"
                    label-field="dicName" value-field="dicCode" v-model:value="formValue.passTypeCode" />
                </NFormItem>-->

                <NFormItem
                  label="入库时间:"
                  path="inTime"
                >
                  <DatePicker
                    input-readonly
                    placeholder="请选择入库时间"
                    clearable
                    :actions="['clear', 'confirm']"
                    class="commonWidth"
                    v-model:formatted-value="formValue.inTime"
                    type="datetime"
                    :is-date-disabled="handleDateStart"
                    @update-formatted-value="handleUpdateStartTime"
                  />
                </NFormItem>
                <NFormItem
                  label="出库时间:"
                  path="outTime"
                >
                  <DatePicker
                    input-readonly
                    placeholder="请选择出库时间"
                    clearable
                    :actions="['clear', 'confirm']"
                    class="commonWidth"
                    type="datetime"
                    v-model:formatted-value="formValue.outTime"
                    :is-date-disabled="handleDate"
                    @update-formatted-value="handleUpdateEndTime"
                  />
                </NFormItem>
                <NFormItem
                  label="入库原因:"
                  path="reasons"
                >
                  <NInput
                    placeholder="请输入入库原因"
                    class="commonWidth"
                    type="textarea"
                    v-model:value="formValue.reasons"
                    clearable
                    :allow-input="stopNull"
                  />
                </NFormItem>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace
        justify="start"
        style="flex: 0 0 42%"
      >
        <NButton
          style="width: 78px; color: #5fb17f"
          ghost
          @click="goBack"
        >
          <template #icon>
            <img
              :src="VBackImg"
              style="width: 25rem; height: 25rem"
            />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton
          type="primary"
          style="background-color: #5faab1"
          @click="confirm(1)"
          v-if="workFlowList?.length"
        >
          保存草稿
        </NButton>
        <NButton
          type="primary"
          @click="confirm(0)"
          v-if="workFlowList?.length"
        >
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal
    :auto-focus="false"
    v-model:show="contentVisible"
    @close="contentVisible = false"
  >
    <VDialogContent
      @close="contentVisible = false"
      @submit="submit"
      title="保存提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 300rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 420rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 400rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.commonWidthB {
  width: 240rem;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
